import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "@/store";
import {getRoutes} from "@/request/Api";

Vue.use(VueRouter)

//公共路由
const routes = [
  {
    path: '/',
    name: 'home',
    redirect: '/first',
    component: () => import(`@/views/HomeViews.vue`),
    children: []
  },
  {
    name: 'about',
    path: '/about',
    component: () => import(`@/views/AboutViews.vue`)
  },
  {
    name: 'login',
    path: '/login',
    component: () => import(`@/views/LoginViews.vue`)
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
//全局token路由守卫
router.beforeEach(async (to, from, next) => {
  //判断是否登录
  const token = localStorage.getItem('authorization-token');
  if (to.path === '/login' && token) {
    next("/")
    return
  }
  if (to.path !== '/login' && !token) {
    next('/login')
    return
  }
  if (token && store.getters["userMenuData/getMenuData"].length == 0) {
    let result = await getRoutes();
    if(!result)return;
    let userPageRoute =[{
      path: "/first",
      title: "首页",
      icon: "star-off"
    }];
    let otherPageRoute = result.data.map(item => {
      if(item.children){
        return {
          path: item.path,
          title: item.meta.title,
          icon: item.meta.icon,
          children: item.children.map(itemx => {
            return {
              path: item.path+'/'+itemx.path,
              icon: itemx.meta.icon,
              title: itemx.meta.title
            }
          })
        }
      }else{
        return {
          path: item.path,
          iocon: item.meta.icon,
          title: item.meta.title
        }
      }
    })
    userPageRoute=[...userPageRoute,...otherPageRoute];
    store.commit("userMenuData/setMenuData", userPageRoute);
    //生成动态路由
    let addRoutes = [{
      path: '/first',
      title: '首页',
      icon: 'star-off',
      meta: {titles: ["首页"]},
      component: () => import(`@/views/FirstViews.vue`)
    }]
    result.data.forEach(item => {
      if (item.children) {
       let addRoute = item.children.map(itemx => {
          return {
            path: item.path+'/'+itemx.path,
            meta: {titles: [item.meta.title, itemx.meta.title]},
            component:  () => import(`@/views/${itemx.name}Views.vue`)
          }
        })
        addRoutes=[...addRoutes,...addRoute]
      }
    });
    addRoutes.forEach(item=>{
      router.addRoute("home",item)
    })
   next(to.path);
   return
  }
  next()
})
export default router
